package com.nuance.assignment.fileInfo.server.util;

import java.io.File;
import java.util.Comparator;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.nuance.assignment.fileInfo.shared.Constants;

/**
 * A comparator for sorting File objects
 * 
 * @author parag
 *
 */
@Component
public class FileComparator implements Comparator<File> {

	private String sortColumn = Constants.NAME;
	private boolean ascending = true;

	@Override
	public int compare(File one, File two) {
		int returnValue = 0;
		if (StringUtils.hasText(sortColumn)) {
			switch (sortColumn) {
			case Constants.PATH:
				returnValue = compare(one.getAbsolutePath(), two.getAbsolutePath());
				break;
			case Constants.LENGTH:
				returnValue = compare(one.length(), two.length());
				break;
			case Constants.CAN_READ:
				returnValue = compare(one.canRead(), one.canWrite());
				break;
			case Constants.CAN_WRITE:
				returnValue = compare(one.canWrite(), two.canWrite());
				break;
			case Constants.CAN_EXECUTE:
				returnValue = compare(one.canExecute(), two.canExecute());
				break;
			case Constants.IS_FILE:
				returnValue = compare(one.isFile(), two.isFile());
				break;
			case Constants.IS_DIRECTORY:
				returnValue = compare(one.isDirectory(), two.isDirectory());
				break;
			case Constants.IS_HIDDEN:
				returnValue = compare(one.isHidden(), two.isHidden());
				break;
			case Constants.IS_ABSOLUTE:
				returnValue = compare(one.isAbsolute(), two.isAbsolute());
				break;
			case Constants.LAST_MODIFIED:
				returnValue = compare(one.lastModified(), two.lastModified());
				break;
			default:
				returnValue = compare(one.getName(), two.getName());
			}
		}
		return ascending ? returnValue : -1 * returnValue;
	}

	private int compare(String one, String two) {
		return one.trim().compareToIgnoreCase(two.trim());
	}

	private int compare(long one, long two) {
		return one == two ? 0 : (one > two ? 1 : -1);
	}

	private int compare(boolean one, boolean two) {
		return one == two ? 0 : (one ? 1 : -1);
	}

	public void setSortColumn(String sortColumn) {
		this.sortColumn = sortColumn;
	}

	public void setAscending(boolean ascending) {
		this.ascending = ascending;
	}

}
